package book;

import utils.AnalyzingBook;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

import static constant.Constant.ALL_BOOK_FILE_NAME;
import static constant.Constant.CAPACITY;

public class Library {
    private Book[] books;
    private int bookCount;
    private AnalyzingBook analyzingBook=new AnalyzingBook();
    Scanner scanner = new Scanner(System.in);

    private static Library library;

    public int getBookCount() {
        return bookCount;
    }

    public void setBookCount(int bookCount) {
        this.bookCount = bookCount;
    }

    private Library(){
        loadAllBooks();
    }


    public static Library getInstance(){
        if(library==null){
            library=new Library();
        }
        return library;
    }
    private void loadAllBooks(){
        books=new Book[CAPACITY];
        Book[] booktmp = analyzingBook.loadObject(ALL_BOOK_FILE_NAME);
        if(booktmp==null){
            bookCount=0;
            return;
        }else{
            if(booktmp.length>=books.length){
                books=new Book[booktmp.length*2];
            }
            for(int i=0;i<booktmp.length;i++){
                books[i]=booktmp[i];
            }
            bookCount=booktmp.length;
        }
    }

    private void storeAllBooks(){
        analyzingBook.storeObject(this.books,ALL_BOOK_FILE_NAME);
    }

    public void addBook(Book book){
        loadAllBooks();
        book.setBookId(bookCount+1);
        books[bookCount++]=book;
        storeAllBooks();
        System.out.println("-----------------------------------");
        System.out.println("图书 "+book.getBookName()+"上架成功！");
        System.out.println("-----------------------------------");
    }
    public void searchBook(){
        System.out.println("查找图书");
        String bookName = scanner.nextLine();
        Book book=searchBookByName(bookName);
        if(book==null){
            System.out.println("没有你要找的这本书，你查找的书名为："+bookName);
        }else{
            System.out.println("找到了你要查找的书，书的详细信息如下：");
            System.out.println(book);
        }
    }

    private Book searchBookByName(String bookName) {
        for (int i = 0; i < bookCount; i++) {
            if (books[i].getBookName().equals(bookName)) {
                return books[i];
            }
        }
        return null;
    }

    public void displayBooks(){
        System.out.println("显示图书");
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }

    public void exit(){
        System.out.println("退出系统");
        System.exit(0);
    }

    public Book searchBookById(int  bookId) {
        loadAllBooks();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId()==bookId){
                return books[i];
            }
        }
        return null;
    }

    private int searchByIdReturnIndex(int bookId){
        loadAllBooks();
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId()==bookId){
                return i;
            }
        }
        return -1;
    }
    public void updateBook(Book book) {
        int index = searchByIdReturnIndex(book.getBookId());
        books[index] = book;
        storeAllBooks();
    }

    public void removeBook(Book removeBook) {
     int index = searchByIdReturnIndex(removeBook.getBookId());
        for (int i = index; i <bookCount-1; i++) {
            books[i]=books[i+1];
        }
        books[bookCount-1]=null;
        storeAllBooks();
        bookCount--;
    }

    public void borrowCount() {
        loadAllBooks();
        for (int i = 0; i < bookCount; i++) {
            System.out.println("书名:"+books[i].getBookName()+
                    " 借阅次数："+books[i].getBorrowCount());
        }
    }

    public void generateBook(int k) {
        loadAllBooks();
        Book[] booktmp = analyzingBook.loadObject(ALL_BOOK_FILE_NAME);
        Arrays.sort(booktmp);
        for (int i = 0; i <k; i++) {
            System.out.println("书名："+ booktmp[i].getBookName()+" 作者："+
                    booktmp[i].getAuthor()+" 借阅次数："+booktmp[i].getBorrowCount());
        }
    }

    public void checkInventoryStatus() {
        loadAllBooks();
        for (int i = 0; i < bookCount; i++) {
            String status = books[i].isBorrowed()?"已借出":"未借出";
            System.out.println("书名："+books[i].getBookName()+" 目前状态："+status);
        }
    }

    public void checkAndRemoveOldBooks() {
        loadAllBooks();
        // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
// 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            //获取当前书籍的上架时间
            LocalDate specifiedDate = books[i].getShelfDate();
            // 计算两个日期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate,
                    currentDate);
            //scanner.nextLine();
            if(yearsBetween >= 1) {
                System.out.print("图书 " + books[i].getBookName() + " 已经上架超过一年，是否移除？ (y/n)：");
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("y")) {
//确认删除调用remove方法进行删除
                    removeBook(books[i]);
                    i--; // 因为后面的书已经向前移动，所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if(!flg) {
            System.out.println("没有上架超过一年的图书！");
        }

    }

    public void borrowBook(int bookId) {
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId()==bookId){
                books[i].setBorrowed(true);
                books[i].increaseBorrowCount();
            }
        }
        storeAllBooks();
    }
    public void returnBook(int bookId) {
        for (int i = 0; i < bookCount; i++) {
            if(books[i].getBookId()==bookId){
                books[i].setBorrowed(false);
                storeAllBooks();
                return;
            }
        }
    }
}

